/**
 * 深度克隆函数（支持循环引用和多种数据类型）
 * @param target 需要克隆的目标值
 * @param hash 用于记录已克隆对象的WeakMap（内部递归使用）
 * @returns 深度克隆后的新值
 */
export function deepClone<T>(target: T, hash = new WeakMap()): T {
    // 处理原始类型和null/undefined
    if (target === null || typeof target !== 'object') {
        return target;
    }

    // 处理特殊对象类型
    if (target instanceof Date) return new Date(target) as T;
    if (target instanceof RegExp) return new RegExp(target) as T;
    if (target instanceof Map) {
        const cloneMap = new Map();
        target.forEach((v, k) => cloneMap.set(deepClone(k, hash), deepClone(v, hash)));
        return cloneMap as T;
    }
    if (target instanceof Set) {
        const cloneSet = new Set();
        target.forEach(v => cloneSet.add(deepClone(v, hash)));
        return cloneSet as T;
    }

    // 处理循环引用
    if (hash.has(target)) {
        return hash.get(target);
    }

    // 处理普通对象和数组
    const cloneTarget = Array.isArray(target) ? [] : {};
    hash.set(target, cloneTarget);

    // 递归克隆属性
    for (const key in target) {
        if (target.hasOwnProperty(key)) {
            (cloneTarget as any)[key] = deepClone((target as any)[key], hash);
        }
    }

    return cloneTarget as T;
}